# Faraday Penetration Test IDE
# Copyright (C) 2016  Infobyte LLC (http://www.infobytesec.com/)
# See the file 'doc/LICENSE' for the license information

import flask
import requests

from flask import Blueprint, abort, make_response, jsonify
from server.utils.logger import get_logger
from server.utils.web import gzipped

exploits_api = Blueprint('exploits_api', __name__)


@gzipped
@exploits_api.route('/v2/vulners/exploits/<cveid>', methods=['GET'])
def get_exploits(cveid):
    """
    Use Vulns API to get all exploits available for a specific CVE-ID
    """

    get_logger(__name__).debug(
        "Request parameters: {!r}".format(flask.request.args))

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json"}

    response = requests.get(
        "https://vulners.com/api/v3/search/id/?references=True&id=" + cveid,
        headers=headers,
        timeout=3
    )

    try:

        json_response = {
            "metasploit": [],
            "exploitdb": [],
            "cveid": cveid
        }

        if response.status_code == 200:

            obj_response = response.json()

            if obj_response["data"]["references"] is not {}:

                metasploit_modules = obj_response["data"]["references"][cveid].get("metasploit", [])
                exploitdb_modules = obj_response["data"]["references"][cveid].get("exploitdb", [])

                for module in metasploit_modules:
                    obj_module = {}
                    obj_module.update({"title": module["title"]})
                    obj_module.update({"id": module["id"]})
                    obj_module.update({"href": module["href"]})
                    json_response["metasploit"].append(obj_module)

                for module in exploitdb_modules:
                    obj_module = {}
                    obj_module.update({"title": module["title"]})
                    obj_module.update({"id": module["id"]})
                    obj_module.update({"href": module["href"]})
                    json_response["exploitdb"].append(obj_module)

    except KeyError as ex:
        abort(make_response(jsonify(message='Could not find {0}'.format(ex.message)), 400))

    return flask.jsonify(json_response)
